const path = require('path')
const fs = require('fs')
const { parseVideoRealUrl } = require('../utils/videoParser')
const { downloadVideo } = require('../utils/downloader')
const { extractAudio } = require('../utils/audioExtractor')
const { callWhisper } = require('../utils/pythonCaller')
const { VIDEO_DIR, AUDIO_DIR, TEXT_DIR } = require('../config/config')

exports.transcribeHandler = async (req, res) => {
    try {
        const { url } = req.query
        if (!url) {
            return res.status(400).json({ error: '缺少视频链接参数' })
        }

        // 1. 解析真实视频直链
        const { title, videoSrcs } = await parseVideoRealUrl(url)
        if (!videoSrcs || videoSrcs.length === 0) {
            return res.status(400).json({ error: '未能解析到视频直链' })
        }
        const videoUrl = videoSrcs[0]

        // 2. 生成唯一文件名
        const ts = Date.now()
        const safeTitle = title ? title.replace(/[^a-zA-Z0-9\-_]/g, '_') : 'video'
        const videoPath = path.join(VIDEO_DIR, `${safeTitle}_${ts}.mp4`)
        const audioPath = path.join(AUDIO_DIR, `${safeTitle}_${ts}.wav`)

        // 3. 下载视频
        await downloadVideo(videoUrl, videoPath)

        // 4. 提取音频
        await extractAudio(videoPath, audioPath)

        // 5. 调用 whisper 语音转文本
        const text = await callWhisper(audioPath)

        // 6. 保存文本到文件
        const textPath = path.join(TEXT_DIR, `${safeTitle}_${ts}.txt`)
        fs.writeFileSync(textPath, text, 'utf-8')

        res.json({
            message: '转写成功',
            title,
            videoUrl,
            videoPath,
            audioPath,
            textPath,
            text
        })
    } catch (err) {
        console.error(err)
        res.status(500).json({ error: '服务器内部错误', detail: err.message })
    }
}

exports.transcribeDirectHandler = async (req, res) => {
    try {
        const { videoUrl, title = 'video' } = req.query
        if (!videoUrl) {
            return res.status(400).json({ error: '缺少视频直链参数' })
        }

        // 生成唯一文件名
        const ts = Date.now()
        const safeTitle = title.replace(/[^a-zA-Z0-9\-_]/g, '_')
        const videoPath = path.join(VIDEO_DIR, `${safeTitle}_${ts}.mp4`)
        const audioPath = path.join(AUDIO_DIR, `${safeTitle}_${ts}.wav`)

        // 下载视频
        await downloadVideo(videoUrl, videoPath)

        // 提取音频
        await extractAudio(videoPath, audioPath)

        // 调用 whisper 语音转文本
        const text = await callWhisper(audioPath)

        // 保存文本到文件
        const textPath = path.join(TEXT_DIR, `${safeTitle}_${ts}.txt`)
        fs.writeFileSync(textPath, text, 'utf-8')

        res.json({
            message: '转写成功',
            title,
            videoUrl,
            videoPath,
            audioPath,
            textPath,
            text
        })
    } catch (err) {
        console.error(err)
        res.status(500).json({ error: '服务器内部错误', detail: err.message })
    }
}